package com.tensquare.article.service;

import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * Created by WF on 2019/9/18 11:18
 */
@Service
@Transactional
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.文章审核

    public void examine(String articleId) {
        articleDao.examine(articleId);
    }
    //2.文章点赞

    public void thumbup(String articleId) {
        articleDao.thumbup(articleId);
    }

    public Article findById(String id) {
        //1.从redis中取出文章对象
        Article article = (Article) redisTemplate.opsForValue().get("article_" + id);
        //2.判断是否存在，如果不存在就从数据库中取
        if(article == null){
            article = articleDao.findById(id).get();
            //将article放到redis中(设置过期时间为10s)
            redisTemplate.opsForValue().set("article_"+id,article,10,TimeUnit.SECONDS);
            System.out.println("将article放到redis中成功！");
        }
        return article;
    }

    public void update(Article article) {
        //1.清理缓存
        redisTemplate.delete("article_" + article.getId());
        articleDao.save(article);
    }

    public void delete(String id) {
        //1.清理缓存
        redisTemplate.delete(id);
        articleDao.deleteById(id);
    }
}
